package com.roy.DubboRPCDemo.protocol.impl;

import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.roy.DubboRPCDemo.bean.RPCResBean;
import com.roy.DubboRPCDemo.bean.UserBean;
import com.roy.DubboRPCDemo.protocol.MyService;
import com.roy.DubboRPCDemo.util.ExecutorManager;

import scala.Tuple2;

public class MyServiceImpl implements MyService{

	private Logger logger = LoggerFactory.getLogger(this.getClass());
	
	public String baseTypeService(int userId, String userName, String userPassword) {
		String res = "received UserInfo: userId => " + userId + ", userName => " + userName + ";userPassword => "
				+ userPassword;
		logger.info(res);
		return res;
	}

	public UserBean mapTypeService(Map<String,String> userinfo) {
		logger.info("get RPC call mapTypeService");
		String userId = userinfo.get("userId");
		String userName = userinfo.get("userName");
		String userPassword = userinfo.get("userPassword");

		UserBean us = new UserBean();
		us.setUserId(Integer.parseInt(userId));
		us.setUserName(userName);
		us.setUserPassword(userPassword);
		us.setUserInfo("set from server");

		return us;
	}

	public UserBean objTypeService(UserBean user) {
		logger.info("get RPC call objTypeService");
		user.setUserInfo("set from server");
		return user;
	}

	public List<UserBean> objArrayService(List<UserBean> users) {
		logger.info("get RPC call objArrayService");
		for (UserBean user : users) {
			user.setUserInfo("set from server");
		}
		return users;
	}

	public RPCResBean frameworkService(String exeId, String[] params) {
		logger.info("get RPC call frameworkService exeId=> " + exeId);
		RPCResBean res = null;
		Tuple2<Object, Method> methodAndObj = ExecutorManager.getMethod(exeId);
//		String[] strParams = convertParam(params);
		if (null != methodAndObj) {
			Object obj = methodAndObj._1;
			Method method = methodAndObj._2;

			try {
				Object invoke = method.invoke(obj, params);
				res = (RPCResBean)invoke;
			} catch (Exception e) {
				logger.error("execute service failed exeId=> " + exeId+";e: "+e.getMessage());
				e.printStackTrace();
//			} catch (IllegalArgumentException e) {
//				logger.error("execute service failed exeId=> " + exeId+";e: "+e.getMessage());
//			} catch (InvocationTargetException e) {
//				logger.error("execute service failed exeId=> " + exeId+";e: "+e.getMessage());
			} 

		}
		logger.info("invoke executor SUCCESSED;res = "+res);
		return null==res?null:res;
	}

	@Override
	public String sayHello(String words) {
		return "Hello "+words;
	}

}
